<script>
import {doDelete, doGet, doPut} from "../http/httpRequest.js";
import {getToken, messageConfirm, messageTip} from "../util/util.js";
import axios from "axios";

export default {
  name: "TransactionView",
  inject: ["reload"],
  data() {
    return {
      // 交易搜索条件
      transactionQuery: {
        customerId: '',
        tranNo: '',
        stage: '',
        expectedDateRange: [] // [开始时间, 结束时间]
      },
      // 交易列表数据
      transactionList: [],
      pageSize: 0,
      total: 0,
      // 交易阶段下拉选项（通过字典接口加载）
      stageOptions: [{}],
      // 复选框选择的交易id数组（用于批量删除）
      transactionIdArray: [],

      tranEditDialogVisible: false,  // 控制编辑弹窗显示
      selectedTransaction: null,     // 当前选中的交易记录
      editedTransaction: {
        stage: '',                // 编辑时选择的阶段
        nextContactTime: ''       // 编辑时选择的下次联系时间
      },
    };
  },
  methods: {
    // 查询交易列表数据
    getData(current) {
      let startTime = '';
      let endTime = '';
      if (
          this.transactionQuery.expectedDateRange &&
          this.transactionQuery.expectedDateRange.length === 2
      ) {
        startTime = this.transactionQuery.expectedDateRange[0];
        endTime = this.transactionQuery.expectedDateRange[1];
      }
      doGet("/api/transactions", {
        current: current,
        customerId: this.transactionQuery.customerId,
        tranNo: this.transactionQuery.tranNo,
        stage: this.transactionQuery.stage,
        startTime: startTime,
        endTime: endTime
      }).then(resp => {
        if (resp.data.code === 200) {
          this.transactionList = resp.data.data.list;
          this.pageSize = resp.data.data.pageSize;
          this.total = resp.data.data.total;
        }
      });
    },
    // 搜索
    onSearch() {
      this.getData(1);
    },
    // 重置搜索条件
    onReset() {
      this.transactionQuery = {};
      this.getData(1);
    },
    // 分页
    toPage(current) {
      this.getData(current);
    },
    // 查看交易详情，跳转到交易详情页面
    viewDetail(id) {
      this.$router.push("/dashboard/tran/detail/" + id);
    },

    // 删除交易
    delTransaction(id) {
      messageConfirm("确定删除该交易记录吗？").then(() => {
        doDelete("/api/transaction/" + id, {}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("删除成功", "success");
            this.reload();
          } else {
            messageTip("删除失败，原因：" + resp.data.msg, "error");
          }
        });
      }).catch(() => {
        messageTip("取消删除", "warning");
      });
    },

    // 处理表格选择
    handleSelectionChange(selection) {
      this.transactionIdArray = selection.map(item => item.id);
    },

    // 批量删除
    batchDel() {
      if (this.transactionIdArray.length <= 0) {
        messageTip("请选择要删除的数据", "warning");
        return;
      }
      messageConfirm("确定要删除这些数据吗？").then(() => {
        let ids = this.transactionIdArray.join(",");
        doDelete("/api/transaction", {ids: ids}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("批量删除成功", "success");
            this.reload();
          } else {
            messageTip("批量删除失败，原因：" + resp.data.msg, "error");
          }
        });
      }).catch(() => {
        messageTip("取消批量删除", "warning");
      });
    },
    // 加载字典数据（如 stage）
    loadDicValue(typeCode) {
      doGet("/api/dicvalue/" + typeCode, {}).then(resp => {
        if (resp.data.code === 200) {
          if (typeCode === "stage") {
            this.stageOptions = resp.data.data;
          }
        }
      });
    },

    // 打开编辑弹窗并加载交易数据
    openEditDialog(transaction) {
      this.selectedTransaction = transaction;  // 记录当前选中的交易
      this.editedTransaction.stage = transaction.stage;
      this.editedTransaction.nextContactTime = transaction.nextContactTime;
      this.tranEditDialogVisible = true;
    },

    // 保存编辑后的数据
    saveTransactionEdit() {
      doPut("/api/transaction/edit", {
        id: this.selectedTransaction.id,
        stage: this.editedTransaction.stage,
        nextContactTime: this.editedTransaction.nextContactTime
      }).then((resp) => {
        if (resp.data.code === 200) {
          messageTip("修改成功", "success");
          this.tranEditDialogVisible = false;
          this.getData(1);  // 重新加载数据
        } else {
          messageTip("修改失败", "error");
        }
      });
    },

    // 批量导出
    batchExportExcel() {
      this.exportExcel(null); // 没有选中的id时导出所有
    },

    // 选择导出
    chooseExportExcel() {
      if (this.transactionIdArray.length <= 0) {
        messageTip("请选择要导出的数据", "warning");
        return;
      }
      messageConfirm("确定要导出这些数据吗?").then(() => {
        let ids = this.transactionIdArray.join(",");
        this.exportExcel(ids);  // 传递选中的ids
      }).catch(() => {
        messageTip("取消批量导出", "warning");
      });
    },

    // 导出Excel
    exportExcel(ids) {
      let token = getToken();
      let iframe = document.createElement("iframe");
      if (ids) {
        iframe.src = axios.defaults.baseURL + "/api/transaction/exportExcel?Authorization=" + token + "&ids=" + ids;
      } else {
        iframe.src = axios.defaults.baseURL + "/api/transaction/exportExcel?Authorization=" + token;
      }
      iframe.style.display = "none";
      document.body.appendChild(iframe);
    },
  },


  mounted() {
    this.loadDicValue("stage");
    this.getData(1);
  }
};
</script>

<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="transactionQuery" style="margin-bottom: 20px;">
      <el-form-item label="交易流水号">
        <el-input v-model="transactionQuery.tranNo" placeholder="请输入交易流水号" clearable/>
      </el-form-item>
      <el-form-item label="交易阶段">
        <el-select v-model="transactionQuery.stage" placeholder="请选择交易阶段" clearable style="width: 180px;">
          <el-option v-for="item in stageOptions" :key="item.id" :label="item.typeValue" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="预计成交日期">
        <el-date-picker
            v-model="transactionQuery.expectedDateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜 索</el-button>
        <el-button type="primary" plain @click="onReset">重 置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-button type="primary" class="btn" @click="batchExportExcel">批量导出(Excel)</el-button>
    <el-button type="success" class="btn" @click="chooseExportExcel">选择导出(Excel)</el-button>

    <!-- 数据展示表格 -->
    <el-table :data="transactionList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column type="index" label="序号" width="60"/>
      <el-table-column property="tranNo" label="交易流水号" show-overflow-tooltip/>
      <el-table-column property="money" label="交易金额" show-overflow-tooltip/>
      <el-table-column label="交易产品">
        <template #default="scope">
          <span>{{ scope.row.productDo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column property="expectedDate" label="预计成交日期" show-overflow-tooltip/>
      <el-table-column label="交易阶段">
        <template #default="scope">
          <span style="color: #67c23a" v-if="scope.row.stage==42"> {{ scope.row.stageDO.typeValue }}</span>
          <span v-else>{{ scope.row.stageDO.typeValue }}</span>
        </template>
      </el-table-column>
      <el-table-column property="createTime" label="创建时间" show-overflow-tooltip/>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="viewDetail(scope.row.id)">详情</el-button>
          <el-button type="success" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗 -->
    <el-dialog
        v-model="tranEditDialogVisible"
        title="编辑交易"
        width="50%"
        center
        draggable
    >
      <el-form :model="editedTransaction" label-width="120px">
        <el-form-item label="交易阶段">
          <el-select
              v-model="editedTransaction.stage"
              placeholder="请选择交易阶段"
              style="width: 100%"
          >
            <el-option
                v-for="item in stageOptions"
                :key="item.id"
                :label="item.typeValue"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="下次联系时间">
          <el-date-picker
              v-model="editedTransaction.nextContactTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择下次联系时间"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="tranEditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTransactionEdit">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="toPage"
    />
  </div>
</template>

<style scoped>
.el-form {
  margin-bottom: 20px;
}
</style>
